package com.lymei.core.modules.system.rest;

import com.lymei.common.exception.BusinessException;
import com.lymei.common.po.ResultResponse;
import com.lymei.core.modules.system.service.IOnlineService;
import com.lymei.core.modules.system.service.SecurityService;
import com.lymei.lib.po.system.LoginUser;
import com.lymei.lib.po.system.UserDetailsImpl;
import com.lymei.lib.vo.system.UserVo;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author lymei
 * @title: AuthController
 * @projectName scui-admin
 * @description: TODO
 * @date 2022/1/2016:03
 */
@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IOnlineService onlineService;

    @PostMapping("/token")
    public ResultResponse login(@RequestBody LoginUser user){
        Authentication authentication;
        authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        var userVo = userDetails.getUser();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = UUID.randomUUID().toString();
        onlineService.put(token,userVo);
        Map<String, Object> result = new HashMap<>();
        result.put("token",token);
        result.put("userInfo",userVo);
        return ResultResponse.success(result);
    }
}
